/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.struts.Exercise.ResolveExercise;

import com.myapp.model.ejercicios.Ejercicios;
import com.myapp.model.resueltos.Resueltos;
import com.myapp.model.usuarios.Usuarios;
import com.myapp.svc.Exercise.ExerciseSvc;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author CarmaZone
 */
public class SelectExercToResolveAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String ERROR = "error";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward res = null;
        String idExerc = request.getParameter("idej");

        //Recojo el usuario y ejercicio en sesión
        HttpSession session = request.getSession();
        Usuarios userSession = (Usuarios) session.getAttribute("usuario");

        //Busco y Recojo el ejercicio seleccionado
        Ejercicios exercSeleccionado = new Ejercicios();
        ExerciseSvc exercSvc = new ExerciseSvc();

        exercSeleccionado = null;
        exercSeleccionado = exercSvc.listarPorId(idExerc);

        //Obtenemos la fecha de hoy
        java.util.Date today = new java.util.Date ();
        java.sql.Timestamp ts = new java.sql.Timestamp (today.getTime());
        
        if (exercSeleccionado != null) {
            //Creo un objeto de ejercicio resuelto
            Resueltos resolve = new Resueltos();
            resolve.setEjercicios(exercSeleccionado);
            resolve.setUsuarios(userSession);
            resolve.setFecha(ts);

            //Pasamos el objeto de seleccionado a resuelto
            try {
                exercSvc.selectExercToResolve(resolve);
                HttpSession ej = request.getSession();
                ej.setAttribute("ej", resolve);
                res = mapping.findForward(SUCCESS);
            } catch (Exception e) {
                res = mapping.findForward(ERROR);
            }
        }

        return res;
    }
}
